package com.iris.netty.review;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

/**
 * @author victor
 */
public class NioServer {
    public static void main(String[] args) throws Exception {

        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(8889));
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while(true){
            selector.select();
            Set<SelectionKey> keys = selector.selectedKeys();
            for (SelectionKey key : keys) {
                if(key.isAcceptable()){
                    ServerSocketChannel keyServerChannel = (ServerSocketChannel) key.channel();
                    SocketChannel acceptChannel = keyServerChannel.accept();
                    acceptChannel.configureBlocking(false);
                    System.out.println("连接成功");
                    acceptChannel.register(selector,SelectionKey.OP_READ);

                }else if (key.isReadable()){
                    SocketChannel readChannel = (SocketChannel) key.channel();

                    System.out.println("接受消息");
                    ByteBuffer byteBuffer = ByteBuffer.allocate(512);
                    int read = readChannel.read(byteBuffer);
                    if(read > 0){
                        byte[] data = byteBuffer.array();
                        String msg = new String(data);
                        System.out.println("服务端收到信息：" + msg);

                        //回写数据
                        ByteBuffer outBuffer = ByteBuffer.wrap("ok".getBytes());
                        readChannel.write(outBuffer);// 将消息回送给客户端
                    }else{
                        System.out.println("客户端关闭");
                        key.cancel();
                    }

                }
            }
            keys.clear();
        }
    }
}
